<template>
  <div class="content">
    <div class="row row-height">
      <div class="left">

        <div class="block">
          <div class="title">基础字段</div>

          <div class="panel">
            <draggable
              v-model="basicsFields"
              v-bind="fieldOption"
              class="panel-drag"
            >
              <div v-for="i in basicsFields" :key="i.id" class="item">
                <img :src="require(`./img/${i.type}.png`)" alt="" />
                <span>
                  {{ i.name }}
                </span>
              </div>
            </draggable>
          </div>
        </div>

        <div class="block">
          <div class="title">高级字段</div>

          <div class="panel">
            <draggable
              v-model="advancedFields"
              v-bind="fieldOption"
              class="panel-drag"
            >
              <div v-for="i in advancedFields" :key="i.id" class="item">
                <img :src="require(`./img/${i.type}.png`)" alt="" />
                <span>
                  {{ i.name }}
                </span>
              </div>
            </draggable>
          </div>
        </div>
      </div>
      <div class="center row-height">
        <div class="top">
          <div class="top-edit" v-if="formNameShow">
            <el-input 
              ref="index"
              v-model="ruleForm.flowName"
              style="width: 100%"
              autofocus
              @blur="blurTitle">
            </el-input>
          </div>
          <h5 v-else @click="formNameShow = true">
            {{ruleForm.flowName}}
          </h5>
          <el-button class="preview" @click="clearForm" size="small">清空</el-button>
        </div>

        <draggable
          v-model="drageFields"
          v-bind="centerOption"
          @add="drageComplete"
          @end="onEnd"
          class="drage-content"
          group="field"
        >
        <template v-if="drageFields.length">
          <div v-for="(i, index) in drageFields" :key="i.ofdid">
            <DrageCenter
              @click="operateDrag"
              :list="i"
              :index="index"
              :nowDrag="nowDrag"
            />
          </div>
        </template>
        <template v-if="!drageFields.length || initStatus">
          <div class="empty">
            <img src="./img/empty.png" alt="">
            <p>拖拽左侧字段创建表单</p>
          </div>
        </template>
        </draggable>
      </div>
      <div class="right" v-if="nowDrag.ofdid">
        <FieldsRight :item="nowDrag" />
      </div>
    </div>

    <el-dialog
      title="表单名称确定"
      :visible.sync="dialogSave"
      width="30%"
      :before-close="closeSave"
    >
      <div class="dialog-save">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="表单名称：" prop="flowName">
            <el-input v-model="ruleForm.flowName"></el-input>
          </el-form-item>
        </el-form>

        <div class="bottom">
          <el-button size="small" @click="closeSave">取消</el-button>
          <el-button
            type="primary"
            size="small"
            @click="confirmSave('ruleForm')"
            >确认</el-button
          >
        </div>
      </div>
    </el-dialog>

    <Preview v-model="dialogVisible" :formData="formData"/>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import {
  PublicFields,
  BasicsFields,
  AdvancedFields,
  SimilarKey,
} from './plugins/fields'
import DrageCenter from './components/Center/index'
import FieldsRight from './components/Right/index'
import Preview from './components/Preview'
import { GetValueType, GetSingle, SetUuid } from './plugins/utils'


export default {
  components: {
    Draggable,
    DrageCenter,
    FieldsRight,
    Preview,
  },

  data () {
    return {
      fields: [],

      publicFields: [],
      basicsFields: [],
      advancedFields: [],
      titleFields: [],

      fieldOption: {
        animation: 300,
        sort: false,
        group: {
          name: 'field',
          pull: 'clone',
          put: false,
        },
      },
      centerOption: {
        animation: 300,
        sort: true,
      },
      drageFields: [],
      nowDrag: {},
      dialogVisible: false,

      dialogSave: false,
      ruleForm: {
        flowName: '表单设计',
      },
      rules: {
        flowName: {
          required: true,
          message: '请输入表单名单',
          trigger: 'blur',
        },
      },

      formNameShow: false,

      formData: {},
      initStatus: false
    }
  },

  provide () {
    return {
      __TFB__: this,
    }
  },

  computed: {
    staticDrageFields () {
      return this.$store.state.contentDrageFields
    },
  },

  watch: {
    staticDrageFields: {
      handler (val) {
        this.drageFields = GetSingle(val)
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    blurTitle () {
      if (!this.ruleForm.flowName) {
        this.ruleForm.flowName = '表单标题'
        this.$error('标题不可以为空')
      }
      this.formNameShow = false
    },
    initData () {
      this.fields = GetSingle([
        // ...PublicFields,
        ...BasicsFields,
        ...AdvancedFields,
      ])

      // this.publicFields = PublicFields
      this.basicsFields = BasicsFields
      this.advancedFields = AdvancedFields

      if (this.$route.query.id) {
        this.initEditData()
        return 
      }


      // 初始数据
      let initList = this.updateListWidth([[PublicFields[0], PublicFields[1]], [PublicFields[2], PublicFields[3]]])
      let nowList = initList.map((item) => {
        return item.map((row) => {
          row.ofdid = `tmp-${SetUuid()}-${row.type}`
          return row
        })
      })
      this.initStatus = true
      this.$store.dispatch('setContentDrageFields', nowList)
    },

    async initEditData () {
      let res = await targetFlowHttp('templateGetById', {
        id: this.$route.query.id,
      })
      this.ruleForm.flowName = res.flowName

      let content = JSON.parse(res.content)
      this.$store.dispatch('setContentDrageFields', content)

      // this.formName = 
    },

    // 修改 文字类型的宽度
    updateListWidth (list) {
      let list1 = GetSingle(list)
      list1.forEach((item) => {
        item.forEach((row) => {
          row.settings.width = 50
        })
      })

      return list1
    },

    preview () {
      if (!this.drageFields.length) {
        this.$error('当前表单没有字段，添加字段后进行预览')
        return
      }

      this.formData = {
        title: this.ruleForm.flowName,
        number: '',
        fields: this.drageFields,
      }
      this.dialogVisible = true
    },

    editH5 () {
      // this.nowDrag = this.titleH5Obj
    },

    save () {
      if (!this.drageFields.length) {
        this.$error('当前表单没有字段, 添加字段后进行保存')
        return
      }
      this.dialogSave = true
    },

    closeSave () {
      this.dialogSave = false
    },

    confirmSave (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let data = {
            flowName: this.ruleForm.flowName,
            content: JSON.stringify(this.staticDrageFields),
            id: this.$route.query.id ? this.$route.query.id : ''
          }
          const res = await targetFlowHttp(this.$route.query.id ? 'templateEdit' : 'templateSave',data)

          window.opener.postMessage('UPDATE_DATA',window.location)
          window.close()
          this.closeSave()
        } else {
          return false
        }
      })
    },

    handleClose () {
      this.dialogVisible = false
    },

    // 中间内容部分拖拽后更新数据
    onEnd (e) {
      let { oldDraggableIndex, newDraggableIndex } = e
      this.drageFields.splice(
        newDraggableIndex,
        0,
        this.drageFields[newDraggableIndex][0]
      )
      this.drageFields.splice(newDraggableIndex, 1)
      this.$store.dispatch('setContentDrageFields', this.drageFields)
    },

    // 在拖拽结束
    drageComplete (e) {
      let { oldDraggableIndex, newDraggableIndex } = e
      this.drageFields = this.setFieldsUuid(this.drageFields)
      this.$store.dispatch('setContentDrageFields', this.drageFields)
      this.initStatus = false
      this.nowDrag = Array.isArray(this.drageFields[newDraggableIndex]) ? this.drageFields[newDraggableIndex][0] : {}
    },
    operateDrag (i) {
      this.nowDrag = i
    },
    // 对每一个拖拽后生成唯一的节点信息
    setFieldsUuid (fields) {
      // 使用JSONparse 不改变原有的
      let fields1 = GetSingle(fields)
      let fields2 = fields1.map((item) => {
        let obj = item
        if (!GetValueType(item, 'array')) {
          //   if (item.type == 52) {
          //     obj = this.setTableId(item)
          //   }
          if (!obj.ofdid) {
            obj = Object.assign({}, SimilarKey, obj)
            obj.ofdid = `tmp-${SetUuid()}-${obj.type}`
          }
          return GetValueType(obj, 'array') ? obj : [obj]
        }
        return obj
      })
      return fields2
    },

    // 给table 设置默认的数据
    setTableId (item) {
      if (item.settings.columns.length > 0) {
        return item
      }
      for (let i = 0; i < 2; i++) {
        let formInfo = GetSingle(SimilarKey)
        formInfo.ofdid = `tmp-${SetUuid()}-${formInfo.type}`
        item.settings.columns.push(formInfo)
      }

      return item
    },

    clearForm () {
      this.$store.dispatch('setContentDrageFields', [])
    }
  },

  mounted () {
    this.initData()
  },
}
</script>

<style lang="less" scoped>
.content {
  width: 100%;
  height: 100%;
  background-color: #f0f3f7;
  overflow-y: hidden;
}

.row {
  display: flex;
  justify-content: space-between;
  margin-top: 4px;
}

.row-height {
  height: 100%;
}

.border {
  border: 1px solid #dcdfe6;
  padding: 12px 16px;
}

.left {
  width: 268px;
  min-height: 670px;
  overflow-y: auto;
  border-radius: 4px;
  background-color: #fff;
  padding: 24px 16px;

  .title {
    color: #494d4c;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 500;
    color: #262a30;
  }

  .panel {
    margin-bottom: 12px;

    .panel-drag {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
    }

    img {
      width: 14px;
      height: 14px;
      margin-right: 8px;
    }
  }

  .item {
    color: #666;
    margin-bottom: 12px;
    cursor: move;
    font-size: 14px;
    width: 110px;
    height: 32px;
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #d9d9d9;
    display: flex;
    align-items: center;
    // justify-content: center;
    text-align: left;
    padding: 0 15px;

    &:hover {
      border: 1px solid #417dff;
      color: #417dff;
    }
  }
}
.center {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #fff;
  overflow-y: hidden;
  margin: 0 24px;
  height: 98%;

  .drage-content {
    // height: 100vh;
    overflow: auto;
    padding-top: 10px;
  }

  .top {
    position: relative;
    text-align: center;
    margin-bottom: 16px;

    .top-edit {
      width: auto;
      margin: 0 auto;
      text-align: center;
      :deep .el-input__inner {
        font-size: 28px;
        font-weight: 500;
        color: #262a30;
        border: 0;
        text-align: center;
      }
    }

    h5 {
      font-size: 28px;
      font-weight: 500;
      color: #262a30;
      line-height: 40px;
    }

    .preview {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
}

.right {
  width: 268px;
  height: 100%;
  overflow-y: auto;
  background: #ffffff;
  padding: 24px;
}

.options-row {
  // .flex(center, '', '', wrap);
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .options-portait {
    margin-right: 20px;
  }
}

.options-portait {
  margin-bottom: 8px;
  color: #494d4c;
  font-size: 14px;
  // .flex(center);
  display: flex;
  align-items: center;

  &::before {
    content: "";
    margin-right: 6px;
    width: 10px;
    height: 10px;
    display: block;
    border: 2px solid darkgray;
  }
}

.dialog-save {
  .bottom {
    text-align: right;
  }
}

.empty {
  border-radius: 3px;
  border: 1px dashed #C4C6CC;
  // display: flex;
  // align-items: center;
  // justify-content: center;
  height: 369px;
  text-align: center;
  font-size: 16px;
  color: #999999;
  padding: 55px 0;
  img {
    width: 318px;
    height: 232px;
  }
}
</style>
